package com.cuit.food.food.Service;

import com.cuit.food.Food;
import com.cuit.food.Resturant;
import com.cuit.food.Usercomment;
import com.cuit.food.VO.ResturantDetail;
import com.cuit.food.VO.ResturantMainPageResult;
import com.cuit.food.VO.RecomondFood;
import com.cuit.food.food.Dao.FoodRepostory;
import com.cuit.food.food.Dao.ResturantReposity;
import com.cuit.food.food.Dao.UserCommentRepository;
import common.result.CodeEnum;
import common.result.ResponseResult;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class DFoodService {
    @Autowired
    FoodRepostory foodRepostory;
    @Autowired
    UserCommentRepository userCommentRepository;
    @Autowired
    ResturantReposity resturantReposity;

    /**
     * 随机食物
     *
     * @return
     */
    public ResponseResult findRecomondFood() {
        RecomondFood recomondFood = new RecomondFood();
        List<Food> breakfirst = foodRepostory.findByIdIsLike("breakfirst%");
        Random random = new Random();
        System.out.println(breakfirst.size());
        int n = random.nextInt(breakfirst.size());
        recomondFood.setBreakfirst(breakfirst.get(n));
        List<Food> dinner = foodRepostory.findByIdIsLike("dinner%");
        n = random.nextInt(dinner.size());
        List<Food> dinners = new ArrayList<>();
        dinners.add(dinner.get(n));
        n = random.nextInt(dinner.size());
        dinners.add(dinner.get(n));
        recomondFood.setDinner(dinners);
        return new ResponseResult(CodeEnum.SUCCESS.getCode(), recomondFood);
    }

    /**
     * 返回所有食物
     *
     * @param food
     * @return
     */
    public ResponseResult findFood(Food food) {
        Specification specification = new Specification<Food>() {
            @Override
            public Predicate toPredicate(Root<Food> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (!StringUtils.isEmpty(food.getCatalog())) {
                    predicateList.add(criteriaBuilder.equal(root.get("catalog"), food.getCatalog()));
                }
                if (!StringUtils.isEmpty(food.getId())) {
                    predicateList.add(criteriaBuilder.equal(root.get("id"), food.getId()));
                }
                if (!StringUtils.isEmpty(food.getName())) {
                    predicateList.add(criteriaBuilder.like(root.get("name").as(String.class), "%" + food.getName() + "%"));
                }
                if (!StringUtils.isEmpty(food.getPrice())) {
                    predicateList.add(criteriaBuilder.equal(root.get("price"), food.getPrice()));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        List all = foodRepostory.findAll(specification);
        return new ResponseResult(CodeEnum.SUCCESS.getCode(), all);
    }

    /**
     * 返回食物表全部内容  评论条数 平均分
     *
     * @return
     */
    public ResponseResult findAllFood() {
        return new ResponseResult(CodeEnum.SUCCESS.getCode(), foodRepostory.findAll());
    }

    public ResponseResult addComment(Usercomment usercomment) {
        userCommentRepository.save(usercomment);
        return new ResponseResult(CodeEnum.SUCCESS.getCode(), "添加成功");
    }

    public ResponseResult findLocated(String rest_id) {
        Resturant resturant = resturantReposity.findById(rest_id).orElse(null);
        return new ResponseResult(CodeEnum.SUCCESS.getCode(), resturant);
    }

    public ResponseResult findAllResturant() {
        List<Resturant> all = resturantReposity.findAll();
        List<ResturantMainPageResult> foodMainPageResultList = new ArrayList<>();

        all.stream().forEach(e -> {
            ResturantMainPageResult foodMainPageResult = new ResturantMainPageResult();
            BeanUtils.copyProperties(e, foodMainPageResult);
            List<Usercomment> scoreList = userCommentRepository.findByResId(e.getId());
            //评论条数
            foodMainPageResult.setCommentCount(scoreList.size());
            int avgScore = 0;
            if (scoreList.size() > 0) {
                avgScore = scoreList.stream().mapToInt(w -> Integer.valueOf(w.getScore())).sum() / scoreList.size();
            }
            //平均分
            foodMainPageResult.setScore(String.valueOf(avgScore));
            foodMainPageResultList.add(foodMainPageResult);
        });
        return new ResponseResult(CodeEnum.SUCCESS.getCode(), foodMainPageResultList);
    }

    public ResponseResult findResturantDetail(String id) {
        List<Resturant> all = resturantReposity.findAll();
        List<ResturantDetail> foodMainPageResultList = new ArrayList<>();

        all.stream().forEach(e -> {
            ResturantDetail resturantDetail = new ResturantDetail();
            resturantDetail.setResturant(e);
            List<Usercomment> scoreList = userCommentRepository.findByResId(e.getId());
            //评论条数
            resturantDetail.setCommentCount(scoreList.size());
            int avgScore = 0;
            if (scoreList.size() > 0) {
                avgScore = scoreList.stream().mapToInt(w -> Integer.valueOf(w.getScore())).sum() / scoreList.size();
            }
            //平均分
            resturantDetail.setScore(String.valueOf(avgScore));
            foodMainPageResultList.add(resturantDetail);
        });
        for (ResturantDetail e : foodMainPageResultList)
            if (e.getResturant().getId().equals(id)) {
                return new ResponseResult(CodeEnum.SUCCESS.getCode(), e);
            }
        return new ResponseResult(CodeEnum.Fail.getCode(), CodeEnum.Fail.getMessage());
    }
}
